// 导入express
const express = require('express')
const cors = require('cors')
const router = require('./router/user')
    //导入 解析jwt 
const { expressjwt: jwt } = require('express-jwt')
const config = require('./config')

// 实例化
const app = express()
    // 全局注册cors 解决跨域问题
app.use(cors())

// 配置解析表单的中间件
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
    //配置全局jwt解析文件
app.use(jwt({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({ path: (/^\/api\//) }))

//注册发送请求处理的中间件
app.use((req, res, next) => {
    res.sd = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

//   导入登录注册路由
const userRouter = require('./router/user')
const Joi = require('joi')
app.use('/api', userRouter)

// 导入用户信息路由
const userInfoRouter = require('./router/userinfo')
app.use('/my', userInfoRouter)

// 导入班级信息路由
const classRouter = require('./router/class')
app.use('/class', classRouter)

// 导入课程信息路由
const courseRouter = require('./router/course')
app.use('/course', courseRouter)

// 导入课程分类路由
const courseCateRouter = require('./router/course_cate')
app.use('/course/cate', courseCateRouter)

// 导入学生信息路由
const stuinfoRouter = require('./router/shuinfo')
app.use('/stuinfo', stuinfoRouter)

// 导入成绩信息路由
const resultsRouter = require('./router/results')
app.use('/results', resultsRouter)

// 导入成绩分类路由
// const resultsCateRouter = require('./router/course_cate')
// app.use('/result/cate', resultsCateRouter)


//注册全局错误中间件
app.use((err, req, res, next) => {
    // 捕获joi 错误对象
    if (err instanceof Joi.ValidationError) return res.sd(err.message)
        // 捕获jwt错误对象
        // if (err.name === 'UnauthorizedError') return res.sd(err.message)
    if (err.name === 'UnauthorizedError') return res.send({
        status: 1,
        message: err.message
    })

})

// 启动服务器
app.listen(3001, () => {
    console.log('server is running at http://127.0.0.1:3001');
})